//
//  YXPhotoPreviewController.m
//  YuanXinCamera
//
//  Created by wangxue on 2016/11/18.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "YXPhotoPreviewController.h"
#import "TZPhotoPreviewCell.h"
#import "UIView+Layout.h"
#import "ALAssetsLibrary+CustomPhotoAlbum.h"
#import "YXModalViewController.h"
#import <Photos/Photos.h>
#import "TZImageManager.h"

#if __has_include(<React/RCTLog.h>)
#import <React/RCTLog.h>
#import <React/RCTUtils.h>
#else
#import <React/RCTLog.h>
#import <React/RCTUtils.h>
#endif

#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#define IOS_VERSION_8_OR_ABOVE (([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)? (YES):(NO))

@interface HudLabel : UILabel

@end

@implementation HudLabel

- (CGSize)intrinsicContentSize {
    
    CGSize contentSize = [super intrinsicContentSize];
    return CGSizeMake(contentSize.width+10, contentSize.height+10);
}

@end

@interface YXPhotoPreviewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UIViewControllerTransitioningDelegate>


@property (nonatomic) UICollectionViewFlowLayout *flowlayout;

@property (nonatomic) NSInteger selecteIndexPath;

@property (nonatomic) UILabel *saveLabel;

@property (nonatomic) HudLabel *comletionLabel;



@end

@implementation YXPhotoPreviewController

- (instancetype)init {
    if (self = [super init]) {
        [self setModalPresentationStyle:UIModalPresentationCustom];
        [self setTransitioningDelegate:self];
        //外面可以单独设置  改变出现的位置大小 默认从屏幕中间出现 50 50
        self.tappedThumbnail = self.view.bounds;
    }
    return self ;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView reloadData];
    [self.view addSubview:self.saveLabel];
    [self.view bringSubviewToFront:self.saveLabel];
    [self comletionLabel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)awakeFromNib {
    
    [self setModalPresentationStyle:UIModalPresentationCustom];
    [self setTransitioningDelegate:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    if(self.models != nil && self.models.count != 0){
        if (self.showFirstIndex <= self.models.count-1)
            self.selecteIndexPath = self.showFirstIndex;
    }else{
        if (self.showFirstIndex <= self.base64Models.count-1)
            self.selecteIndexPath = self.showFirstIndex;
    }
    NSString *str = [NSString stringWithFormat:@"%d",self.showFirstIndex];

    RCTLog(@"%@",str);
    
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.showFirstIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
     RCTLog(@"%@",str);
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.saveLabel.frame = CGRectMake(self.view.frame.size.width-50, 20, 50, 40);
}

//相册使用权限
- (BOOL)PhotosjudgeIsHavePhotoAblumAuthority {
#if __has_include(<Photos/Photos.h>)
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    // 家长控制,不允许访问
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        return NO;
    }
#else
    ALAuthorizationStatus state = [ALAssetsLibrary authorizationStatus];
    // 家长控制,不允许访问
    if (state == ALAuthorizationStatusRestricted || state == ALAuthorizationStatusDenied) {
        return NO;
    }
#endif
    
    return YES;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[YXModalViewController alloc] initWithThumbail:self.tappedThumbnail];
    
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [[YXModalViewController alloc] initWithThumbail:self.tappedThumbnail];
}

#pragma mark - UICollectionView Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(self.models != nil && self.models.count != 0)
        return self.models.count;
    else
        return self.base64Models.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZPhotoPreviewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.tag = indexPath.row;
    RCTLog(@"开始绘制");
    if(self.cellImageLoader == nil)
        return cell;
    RCTLog(@"判断models是否为空");
    YXAssetModel *assetModel = nil;
    if(self.models != nil && self.models.count != 0){
        RCTLog(@"从imageList获取数据");
        assetModel = self.models[indexPath.row];
    } else {
        RCTLog(@"从imageBase64List获取数据");
        assetModel = self.base64Models[indexPath.row];
    }
    assetModel.selectIndex = indexPath.row;
    __block TZPhotoPreviewCell *previewCell = cell;
    
    // 先设置占位图 placeholder
    previewCell.previewView.imageView.image = [UIImage imageNamed:@"YuanXinCamera.bundle/place"];
    [previewCell recoverSubviews];
    
    // 存在 base64
    if (assetModel.imageBase64 && assetModel.imageBase64.length > 0) {
        // 将base64字符串转为NSData
        NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:assetModel.imageBase64 options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
        // 将NSData转为UIImage
        UIImage *decodedImage = [UIImage imageWithData: decodeData];
        previewCell.previewView.imageView.image = decodedImage;
        [previewCell recoverSubviews];
    } else if (assetModel.imageURL && assetModel.imageURL.absoluteString.length > 0) {
        [self.cellImageLoader cellLazyImageWithAssetModel:assetModel completionBlock:^(UIImage *image, NSInteger tag) {
            if(image){
                if(previewCell.tag == tag){
                    // UI要在主线程更新，不然不知道什么时候刷新UI，造成加载慢的假象。。
                    RCTExecuteOnMainQueue(^{
                        previewCell.previewView.imageView.image = image;
                        [previewCell recoverSubviews];
                    });
                    RCTLog(@"cellLazyImageWithAssetModel coback");
                }else {
                    RCTLog(@"cellLazyImageWithAssetModel previewCell null");
                }
            }
        }];
    } else if (assetModel.YXAsset != nil) {
        [[TZImageManager manager] getPhotoWithAsset:assetModel.YXAsset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            previewCell.previewView.imageView.image = photo;
            [previewCell recoverSubviews];
        }];
    }
    cell.singleTapGestureBlock = ^(){
        [self dismissViewControllerAnimated:YES completion:nil];
    };
    
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    if (offset.x == 0) {
        self.selecteIndexPath =  0;
    }else {
        NSInteger row = offset.x/CGRectGetWidth(scrollView.frame);
        self.selecteIndexPath = row;
    }
}



#pragma mark - action

- (void)saveImage{
    
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    if (!appName)appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
    
    if (![self PhotosjudgeIsHavePhotoAblumAuthority]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请在iPhone的设置-隐私->允许%@访问你的照片",appName] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (IOS_VERSION_8_OR_ABOVE) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            } else {
                // 私有API上线会被拒
                //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
            }
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:sureAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
        return;
    }
    self.saveLabel.enabled = NO;
    TZPhotoPreviewCell *cell = (TZPhotoPreviewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.selecteIndexPath inSection:0]];
    UIImage *image = cell.previewView.imageView.image;
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library saveImage:image toAlbum:appName completion:^(NSURL *assetURL, NSError *error) {
        dispatch_main_async_safe(^{
            [UIView animateKeyframesWithDuration:1.0 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
                [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:1/2.0 animations:^{
                    self.comletionLabel.hidden = NO;
                    self.comletionLabel.text = @"已保存";
                    self.comletionLabel.alpha = 1.0;
                }];
                [UIView addKeyframeWithRelativeStartTime:1/2.0 relativeDuration:1/2.0 animations:^{
                    self.comletionLabel.alpha = 0.0;
                }];
            } completion:^(BOOL finished) {
                self.saveLabel.enabled = YES;
                self.comletionLabel.hidden = YES;
            }];
        });
        
        
    } failure:^(NSError *error) {
        dispatch_main_async_safe(^{
            
            [UIView animateKeyframesWithDuration:1.0 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
                [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:1/2.0 animations:^{
                    self.comletionLabel.hidden = NO;
                    self.comletionLabel.text = @"再试一次";
                    self.comletionLabel.alpha = 1.0;
                }];
                [UIView addKeyframeWithRelativeStartTime:1/2.0 relativeDuration:1/2.0 animations:^{
                    self.comletionLabel.alpha = 0.0;
                }];
                
            } completion:^(BOOL finished) {
                self.saveLabel.enabled = YES;
                self.comletionLabel.hidden = YES;
                
                
            }];
            
            
        });
        
        
    }];
    
}
#pragma mark - Lazy Load

- (UICollectionViewFlowLayout *)flowlayout {
    if (!_flowlayout) {
        _flowlayout = [UICollectionViewFlowLayout alloc];
        _flowlayout.minimumLineSpacing = 0;
        _flowlayout.minimumInteritemSpacing = 0;
        
        _flowlayout.itemSize = CGSizeMake(self.view.tz_width + 20, self.view.tz_height);
        _flowlayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
    }
    return _flowlayout;
}

- (UICollectionView *)collectionView {
    
    if (_collectionView == nil)
        
    {
        _collectionView =  [[UICollectionView alloc] initWithFrame:CGRectMake(-10, 0, self.view.tz_width + 20, self.view.tz_height) collectionViewLayout:self.flowlayout];
        _collectionView.backgroundColor = [UIColor blackColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.scrollsToTop = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.contentOffset = CGPointMake(0, 0);
        [_collectionView registerClass:[TZPhotoPreviewCell class] forCellWithReuseIdentifier:@"cell"];
        [self.view addSubview:_collectionView];
        
    }
    return _collectionView;
}

- (UILabel *)saveLabel {
    if (!_saveLabel) {
        _saveLabel = [UILabel new];
        _saveLabel.text = @"保存";
        _saveLabel.textColor = [UIColor whiteColor];
        _saveLabel.font = [UIFont systemFontOfSize:15];
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(saveImage)];
        [_saveLabel addGestureRecognizer:recognizer];
        _saveLabel.userInteractionEnabled = YES;
    }
    return _saveLabel;
}

- (HudLabel *)comletionLabel {
    if(!_comletionLabel) {
        _comletionLabel = [HudLabel new];
        _comletionLabel.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
        _comletionLabel.font = [UIFont systemFontOfSize:15];
        _comletionLabel.textColor = [UIColor whiteColor];
        _comletionLabel.textAlignment = NSTextAlignmentCenter;
        _comletionLabel.numberOfLines = 1;
        _comletionLabel.text = @"已保存";
        _comletionLabel.layer.cornerRadius = 5.0;
        _comletionLabel.layer.masksToBounds = YES;
        [self.view addSubview:_comletionLabel];
        _comletionLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_comletionLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_comletionLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
        _comletionLabel.alpha = 0.0;
        _comletionLabel.hidden = YES;
    }
    return _comletionLabel;
}

- (void)setModels:(NSArray<YXAssetModel *> *)models {
    _models = models;
}

- (void)setShowFirstIndex:(NSInteger)showFirstIndex {
    _showFirstIndex = showFirstIndex;
    self.selecteIndexPath = showFirstIndex;
}


@end
